<template>
  <el-container class="userContainer">
    <el-aside class="userPaneLUser">
      <el-tooltip class="add" effect="light" :content="$t('添加用户组')" placement="bottom-start">
        <el-button type="success" icon="el-icon-plus" size="mini" @click="groupDialogVisible"></el-button>
      </el-tooltip>
      <el-tooltip class="edit" effect="light" :content="$t('编辑用户组')" placement="bottom-start">
        <el-button type="success" icon="el-icon-edit" size="mini" @click="groupDialogVisible(groupNode, 'editTop')"></el-button>
      </el-tooltip>
      <el-tooltip class="del" effect="light" :content="$t('删除用户组')" placement="bottom-start">
        <el-button type="danger" icon="el-icon-close" size="mini" @click="deleteGroup(groupStr)"></el-button>
      </el-tooltip>
      <el-tooltip class="finds" effect="light" :content="$t('查询用户组下的用户！')" placement="bottom-start">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="listData()"></el-button>
      </el-tooltip>
      <div class="userTreeOutBorder">
        <el-tree :props="props" class="userTreeGroup" ref="userTreeGroup" :data="groupList" node-key="id" show-checkbox @check-change="handleCheckChange" default-expand-all @node-contextmenu='openMenu' :check-strictly='true'>
        </el-tree>
      </div>
      <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
        <li @click="groupDialogVisible(selectedTag, 'add')" class="del">{{$t('添加')}}</li>
        <li @click="groupDialogVisible(selectedNode, 'edit')" class="edit">{{$t('编辑')}}</li>
        <li @click="deleteGroup(selectedTag)" class="del">{{$t('删除')}}</li>
        <li @click="listData(selectedTag)" class="check">{{$t('查询用户')}}</li>
      </ul>
      <group-dialog v-if="GroupDialogVisible" @userGroupData='userGroupData' ref="refGroupDialogVisible"></group-dialog>
    </el-aside>
    <el-main class="strategyFatherBox" style="width: 100%;padding:5px 20px;">
      <el-button type="success" size='small' @click="dialogVisible()" style="margin-left:10px;" class="addClick">{{$t('添加')}}</el-button>
      <el-button type="danger" size='small' @click="deleteUser" class="delClick">{{$t('删除')}}</el-button>
      <el-table size='mini' ref="multipleTable" :data="userList" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align='center' width="55"></el-table-column>
        <el-table-column prop="name" align='center' :label="$t('名称')">
          <template slot-scope="scope">
            <tooltip :copyText="scope.row.name" class="wid190">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="fname" align='center' :label="$t('所属组')" :formatter="fnameFormatter">
          <template slot-scope="scope">
            <tooltip :copyText="fgroupShow(scope.row)" class="wid190">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="atype" align='center' min-width="100" :label="$t('认证方式')">
          <template slot-scope="scope">
            {{ $t(atypeList[scope.row.atype]) }}
          </template>
        </el-table-column>
        <el-table-column prop="aserver" align='center' :label="$t('关联服务器')">
          <template slot-scope="scope">
            <tooltip :copyText="scope.row.aserver" class="wid190">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="desc" align='center' :label="$t('描述')">
          <template slot-scope="scope">
            <tooltip :copyText="scope.row.desc" class="wid190">
            </tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" align='center' min-width="100" :label="$t('状态')">
          <template slot-scope="scope">
            {{ $t(statusList[scope.row.status]) }}
          </template>
        </el-table-column>
        <el-table-column prop="ref" align='center' min-width="100" :label="$t('引用计数')"></el-table-column>
        <el-table-column align='center' fixed="right" :label="$t('操作')" width="100">
          <template slot-scope="scope">
            <el-button type="success" plain size="mini" @click="dialogVisible(scope.row)" :class="'edit' + (scope.$index + 1)">{{$t('编辑')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <user-dialog v-if="UserDialogVisible" @listData='listData' ref="refUserDialogVisible"></user-dialog>
    </el-main>
  </el-container>
</template>
<script>
import { getUserArray, getGroupUserInfo, delUser, delGroup } from '@/api/user/user'
// import splitPane from 'vue-splitpane'
import UserDialog from './components/UserDialog.vue'
import GroupDialog from './components/GroupDialog.vue'

export default {
  name: 'user',
  // splitPane
  components: { UserDialog, GroupDialog },
  data () {
    return {
      UserDialogVisible: false,
      GroupDialogVisible: false,
      userList: [],
      groupList: [],
      groupIndex: {},
      selectList: [],
      nameStr: '',
      groupStr: '',
      groupNode: [],
      props: {
        label: 'name',
        children: 'children'
      },
      visible: false,
      top: 0,
      left: 0,
      statusList: {
        'able': '启用',
        'disable': '禁用'
      },
      atypeList: {
        'no-connect': '暂不关联',
        'local-auth': '本地认证',
        'third-auth': '第三方认证'
      },
      selectedTag: null,
      selectedNode: null,
      nowName: null
    }
  },
  watch: {
    visible (value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  created () {
    this.listData()
    this.userGroupData()
  },
  methods: {
    userGroupData () {
      getUserArray().then(res => {
        if (res.status === 0) {
          var groupList = []
          this.groupIndex = {}
          res.info.forEach((item, index) => {
            if (item.name === item.pname) {
              groupList.push({ children: [], id: item.id, name: item.name, ip_type: item.itype, father_group: item.pname, desc: item.desc })
              this.groupIndex[item.name] = String(index)
            } else {
              let parent = groupList
              this.groupIndex[item.pname].split(',').forEach((index, ind) => {
                if (ind === this.groupIndex[item.pname].split(',').length - 1) {
                  parent = parent[index]
                } else {
                  parent = parent[index].children
                }
              })
              parent.children.push({ children: [], id: item.id, name: item.name, ip_type: item.itype, father_group: item.pname, desc: item.desc })
              this.groupIndex[item.name] = String(this.groupIndex[parent.name] + ',' + (parent.children.length - 1))
            }
          })
          this.groupList = groupList
        }
      })
    },
    handleCheckChange (data, value) {
      this.groupNode = this.$refs.userTreeGroup.getCheckedNodes()

      var groupStr = ''
      for (var item of this.groupNode) {
        if (groupStr === '') {
          groupStr = item.name
        } else {
          groupStr = groupStr + '@#@' + item.name
        }
      }
      this.groupStr = groupStr
    },
    // 多选按钮
    handleSelectionChange (data) {
      this.selectList = data
      var nameStr = ''
      for (var item of data) {
        if (nameStr === '') {
          nameStr = item.name
        } else {
          nameStr = nameStr + '@#@' + item.name
        }
      }
      this.nameStr = nameStr
    },
    // 列表
    listData (data) {
      if (data || (this.groupStr.indexOf('@#@') < 0) || !this.groupStr) {
        getGroupUserInfo({ name: data || this.groupStr || 'root' }).then(res => {
          if (res.status === 0) {
            this.userList = res.info
            this.nowName = data || this.groupStr || 'root'
          }
        })
      } else {
        this.$messages.error(this.$t('请选择一条数据进行操作'))
      }
    },
    // 添加按钮
    dialogVisible (data) {
      this.UserDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refUserDialogVisible.init(data, this.nowName)
      })
    },
    groupDialogVisible (data, type) {
      switch (type) {
        case 'edit':
          if (data && data.name === 'root') {
            this.$messages.error(this.$t('root组不允许修改！'))
          } else {
            this.GroupDialogVisible = true
            this.$nextTick(() => {
              this.$refs.refGroupDialogVisible.init(data, type)
            })
          }
          break
        case 'editTop':
          if (data && data[0] && data[0].name === 'root') {
            this.$messages.error(this.$t('root组不允许修改！'))
          } else if (data && data.length === 1) {
            this.GroupDialogVisible = true
            this.$nextTick(() => {
              this.$refs.refGroupDialogVisible.init(data[0], type)
            })
          } else {
            this.$messages.error(this.$t('请选择一条数据进行操作'))
          }
          break
        case 'add':
          this.GroupDialogVisible = true
          this.$nextTick(() => {
            this.$refs.refGroupDialogVisible.init(data, type)
          })
          break
        default:
          this.GroupDialogVisible = true
          this.$nextTick(() => {
            this.$refs.refGroupDialogVisible.init()
          })
          break
      }
    },
    deleteGroup (data) {
      if (data) {
        this.$confirm(this.$t('您是否要删除所有选中的数据？'), this.$t('提示'), {
          closeOnClickModal: false,
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          confirmButtonClass: 'confirmButton',
          cancelButtonClass: 'confirmCancelButton',
          type: 'warning'
        }).then(() => {
          delGroup({ name: data || this.groupStr }).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t('删除成功'),
                type: 'success'
              })
              this.groupStr = ''
              this.groupNode = []
              this.userGroupData()
              this.listData((this.nowName === (data || this.groupStr)) ? 'root' : this.nowName)
            }
          })
        })
      } else {
        this.$messages.error(this.$t('请至少选择一条数据进行删除'))
      }
    },
    deleteUser () {
      if (this.nameStr) {
        this.$confirm(this.$t('您是否要删除所有选中的数据？'), this.$t('提示'), {
          closeOnClickModal: false,
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          confirmButtonClass: 'confirmButton',
          cancelButtonClass: 'confirmCancelButton',
          type: 'warning'
        }).then(() => {
          delUser({ name: this.nameStr }).then(res => {
            if (res.status === 0) {
              this.$message({
                message: this.$t('删除成功'),
                type: 'success'
              })
              this.nameStr = ''
              this.listData(this.nowName)
            }
          })
        })
      } else {
        this.$messages.error(this.$t('请至少选择一条数据进行删除'))
      }
    },
    fnameFormatter (row) {
      let fname = ''
      row.fgroup.forEach((item, index) => {
        if (index === 0) {
          fname += item.pname
        } else {
          fname += ',' + item.pname
        }
      })
      return fname
    },
    openMenu (e, tag) {
      const menuMinWidth = 200
      const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
      const offsetWidth = this.$el.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft + 15 // 15: margin right

      if (left > maxLeft) {
        this.left = maxLeft
      } else {
        this.left = left
      }

      this.top = e.clientY - 60
      this.visible = true
      this.selectedTag = tag.name
      this.selectedNode = tag
    },
    closeMenu () {
      this.visible = false
    },
    fgroupShow (row) {
      let retext = []
      if (row.fgroup && row.fgroup.length > 0) {
        for (let item of row.fgroup) {
          retext.push(item.pname)
        }
      }
      return retext.join(',')
    }
  }
}
</script>
<style lang="less">
.userTreeGroup {
  min-width: 230px;
  display: inline-block;

  .el-tree-node {
    >.el-tree-node__children {
      overflow: unset;
    }
  }
}

.userTreeOutBorder {
  width: 230px !important;
  padding: 0;
  margin: 0;
  overflow-x: auto;
  height: calc(100vh - 172px);
}
</style>
<style lang="less" scoped>
.userContainer {
  height: calc(100vh - 138px);
}

.userPaneLUser {
  padding: 0;
  margin: 0;
  background-color: #fff;
  font-size: 18px;
  border-right: 1px solid #ddd;
  width: 240px !important;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;
    line-height: 16px;

    &:hover {
      background: #eee;
    }
  }
}
</style>
